package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.other.config.exception.BusinessException;
import cn.itsource.basic.service.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.domain.LoginInfo;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service //交给spring管理
public class EmployeeServiceImpl extends BaseServiceImpl<Employee,EmployeeQuery> implements IEmployeeService {

    @Autowired
    private RedisService redisService;

    /**
     * 注入mapper
     */
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 登录业务
     * @param employee  用户名 密码都在里面
     * @return
     */
    @Override
    public AjaxResult login(Employee employee) {

        //1.根据用户名查询用户信息   //账户名与密码不匹配，请重新输入
        Employee dbEmployee = employeeMapper.selectByUsername(employee);
        //1.1.如果查不到，直接抛异常
        Optional.ofNullable(dbEmployee).orElseThrow(()->new BusinessException("账户名与密码不匹配，请重新输入1"));

        //2.比对密码（大坑） 对传进来密码加盐加密  和 数据库的密码串进行比对
        //对传进来密码加盐加密                        old盐:从数据库查询的对象中来                     传进来的密码
        String pagePwd = MD5.create().setSalt(dbEmployee.getSalt().getBytes()).digestHex(employee.getPassword());

        //2.1比对不通过，抛异常
        if (!StringUtils.equals(pagePwd,dbEmployee.getPassword())){
            throw new BusinessException("账户名与密码不匹配，请重新输入2");
        }

        //3.成功的登录信息放到redis  key：token字符串  value：登录信息
        String token = IdUtil.fastSimpleUUID();//令牌
        //3.1封装通用的登录对象
        LoginInfo loginInfo = BeanUtil.copyProperties(dbEmployee, LoginInfo.class);
        loginInfo.setToken(token);
        loginInfo.setShopId(dbEmployee.getShopId());
        //3.2存redis 30分钟
        redisService.setStringKeyAndValue(token,loginInfo,30);

        //4.返回信息
        return AjaxResult.createSuccess(loginInfo);
    }

    @Override
    public List<Employee> findShopEmployees() {
        return employeeMapper.findShopEmployees();
    }


    @Override
    public List<Employee> findManagers() {
        return employeeMapper.findManagers();
    }



}
